package persistent.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.Transaction;

import basic.HibBaseDAO;
import basic.HibernateSessionFactory;
import model.TCheckReport;
import model.TCheckReportItem;
import model.TStudent;
import model.VReportImport;
import persistent.dao.DataImportDAO;
import persistent.factory.DAOFactory;
import util.toolkit.Constant;
import util.toolkit.Expression;
import util.toolkit.ListUtil;
import util.toolkit.LogUtil;

/**
 * 数据导入业务接口实现类
 * @author 徐震霖
 * @since 2018-12-09 16:29
 */
public class DataImportImpl implements DataImportDAO {

	private HibBaseDAO dao=null;
	private static final Log log = LogFactory.getLog(HibBaseDAO.class);
	
	public DataImportImpl() {
		dao = new HibBaseDAO();
	}
	
	/**
	 * 保存一个测评报告
	 * @param report 测评报告对象
	 * @return  成功返回主键编号，失败
	 */
	@Override
	public int saveTCheckReport(TCheckReport report) {		
		return dao.insert(report);
	}
	
	/**
	 * 批量导入学生测评（EPQ，MHT）结果
	 * @param rImports 测评结果视图对象列表
	 * @return 成功返回true，失败返回false
	 */
	@Override
	public boolean importEPQandMHTList(List<VReportImport> rImports) {
		
		Session session1 = HibernateSessionFactory.getSession();
		Transaction tx1 = null; 
		tx1 = session1.beginTransaction();
		boolean issuc = true;
		
		try {
			List<TStudent> studentlist = new ArrayList<TStudent>();
			//int l = 0;
			for (VReportImport vReportImport : rImports) {
				if(!DAOFactory.getStudentDAO().isexist(vReportImport.getUsername())){					
					//System.out.println("不存在" + ++l + "：" + vReportImport.getUsername());
					TStudent student = new TStudent();
					student.setBirthday(vReportImport.getBirthday());
					student.setClassid(vReportImport.getClassId());
					student.setRealName(vReportImport.getRealName());
					student.setSchoolid(vReportImport.getSchoolid());
					student.setSex(vReportImport.getSex());
					student.setIdnumber(vReportImport.getUsername());
					studentlist.add(student);
				}
			}
			
			List<String> stuids = new ArrayList<String>();
			int stuidSize = 0;
			
			List<TStudent> removeStudents = ListUtil.removeDuplicate(studentlist);

			for (int i = 0; i < removeStudents.size(); i++) {
				String classid = studentlist.get(i).getClassid();
				if (i == 0) {
					Expression exp = new Expression();
					exp.andLike("stuid", classid, String.class);
					String hql = "from VStudent " + exp.toString();
					List<TStudent> students = dao.select(hql);
					if (students != null) {
						stuidSize = students.size();
					} else {
						if (tx1 != null) tx1.rollback();
						session1.close(); // 关闭连接
						return false;
					}
				}
				if (stuidSize == 0) {
					if (i + 1 <= 9) {
						stuids.add(classid + "00" + (i + 1));
					} else if (i + 1 > 9 && i + 1 < 99) {
						stuids.add(classid + "0" + (i + 1));
					} else {
						stuids.add(classid + (i + 1));
					}
				} else if (stuidSize > 0 && stuidSize < 9) {
					if (stuidSize + i + 1 <= 9) {
						stuids.add(classid + "00" + (stuidSize + i + 1));
					} else if (stuidSize + i + 1 > 9 && stuidSize + i + 1 < 99) {
						stuids.add(classid + "0" + (stuidSize + i + 1));
					} else {
						stuids.add(classid + (stuidSize + i + 1));
					}
				} else {
					if (stuidSize + i + 1 <= 9) {
						stuids.add(classid + "00" + (stuidSize + i + 1));
					} else if (stuidSize + i + 1 > 9 && stuidSize + i + 1 < 99) {
						stuids.add(classid + "0" + (stuidSize + i + 1));
					} else {
						stuids.add(classid + (stuidSize + i + 1));
					}
				}
			}
			
			//int k = 0;			
			for (int i = 0; i < removeStudents.size(); i++) {				
				//System.out.println("插入 " + ++k + " ：" + tStudent.getStuid());
				TStudent tStudent = removeStudents.get(i);
				tStudent.setPwd(Constant.STARTPASSWORD);
				tStudent.setStuid(stuids.get(i));
				session1.save(tStudent);
			}
			
			for (VReportImport vReportImport : rImports) {
				TCheckReport checkReport = new TCheckReport();
				checkReport.setChecktime(vReportImport.getChecktime());
				checkReport.setChecktypeid(vReportImport.getChecktypeid());
				checkReport.setGradeyear(vReportImport.getGradeyear());
				checkReport.setItemscorestr(vReportImport.getItemscorestr());
				checkReport.setUsername(vReportImport.getUsername());
				//得到报告自动编号
				int row = 0;
				//int i = 0;
//				System.out.println("第" + ++i + "个");
//				System.out.println("用户名：" + vReportImport.getUsername() + "，真实姓名：" + 
//				vReportImport.getRealName() + "，报告类型：" + vReportImport.getChecktypeid());
				
				Serializable key = session1.save(checkReport);
				row = ((Integer)key).intValue();
								
				List<TCheckReportItem> itemlist = vReportImport.getCheckitems();
				for (TCheckReportItem tCheckReportItem : itemlist) {
					tCheckReportItem.setCheckid(row);
					session1.save(tCheckReportItem);
				}		
			}
		} catch (Exception e) {
			issuc = false;
			log.error("persistent.impl.DataImportImpl类importEPQandMHTList(List<VReportImport> rImports)方法调用错误：");
			log.error(LogUtil.getMsg(e));
			System.out.println("persistent.impl.DataImportImpl类importEPQandMHTList(List<VReportImport> rImports)方法调用错误：");
			e.printStackTrace();
		}
		
		if(tx1 != null && issuc){
			tx1.commit();
			session1.close(); //关闭连接
			return true;
		}
		else if(tx1 != null && !issuc){
			tx1.rollback();
			session1.close(); //关闭连接			
		}
		return false;
	}

}
